﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace org.googlecoders.GetLatestChromium
{
	[XmlRoot("buildlocation")]
	public class BuildLocation : IEqualityComparer<BuildLocation>
	{
		[XmlAttribute("name")]
		public string Name = "Default";

		[XmlAttribute("url")]
		public string Url = "http://build.chromium.org/f/chromium/snapshots/Win_Webkit_Latest/";

		[XmlAttribute("latest")]
		public string Latest = "LATEST";

		[XmlAttribute("revisions")]
		public string Revisions = "REVISIONS";

		[XmlAttribute("changelog")]
		public string ChangeLog = "changelog.xml";

		[XmlAttribute("exe")]
		public string Exe = "mini_installer.exe";
		
		public BuildLocation()
		{
		}
		
		public BuildLocation(string name, string url, string latest)
		{
			Name = name;
			Url = url;
			Latest = latest;
		}
		
		public static List<BuildLocation> DefaultLocations = new List<BuildLocation>{
			new BuildLocation("Snapshots","http://commondatastorage.googleapis.com/chromium-browser-snapshots/Win/", "LAST_CHANGE"),
			new BuildLocation("Continuous", "http://commondatastorage.googleapis.com/chromium-browser-continuous/Win/", "LAST_CHANGE"),
			new BuildLocation("Webkit", "http://build.chromium.org/f/chromium/snapshots/Win_Webkit_Latest/", "LATEST")
		};
		
		private static List<BuildLocation> _locations = null;
		public static List<BuildLocation> GetLocations()
		{
			if(_locations != null)
				return _locations;
				
			List<BuildLocation> ret = new List<BuildLocation>();
			XmlSerializer serializer = new XmlSerializer(typeof(List<BuildLocation>), new XmlRootAttribute("buildlocations"));
			if(File.Exists("locations.xml"))
			{
				using(StreamReader sr = new StreamReader("locations.xml"))
				{
					ret = (List<BuildLocation>)serializer.Deserialize(sr);
					sr.Close();
				}
			}
			ret.AddRange(BuildLocation.DefaultLocations.Except<BuildLocation>(ret, new BuildLocation()));
			_locations = ret;
			return ret;
		}
	
		public static string ExportLocations()
		{
			GetLocations();
			
			string ret = null;
			XmlSerializer serializer = new XmlSerializer(typeof(List<BuildLocation>), new XmlRootAttribute("buildlocations"));
			using (StreamWriter sw = new StreamWriter("locations.xml"))
			{
				serializer.Serialize(sw, _locations);
				sw.Close();
			}
			if(File.Exists("locations.xml"))
				ret = new FileInfo("locations.xml").FullName;
			return ret;	
		}

		#region IEqualityComparer<BuildLocation> Members

		public bool Equals(BuildLocation x, BuildLocation y)
		{
			return x.Name == y.Name;
		}

		public int GetHashCode(BuildLocation obj)
		{
			return obj.Name.GetHashCode();
		}

		#endregion
	}
}
